package com.loopy.tomcat.http;

import java.io.*;
import java.util.HashMap;

public class loopyRequest {
    private String method;
    private String uri;
    private HashMap<String, String> parameterMapping = new HashMap<>();
    private InputStream inputStream=null;

    public loopyRequest(InputStream inputStream) {
        this.inputStream=inputStream;
        ecspHttpRequest();
    }
    private void ecspHttpRequest() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
            String requestLine = br.readLine();
//            System.out.println(requestLine);
            String[] requestLineAddr = requestLine.split(" ");
            method = requestLineAddr[0];
            int index = requestLineAddr[1].indexOf("?");
            if (index == -1) {
                uri = requestLineAddr[1];

            } else {
                uri = requestLineAddr[1].substring(0, index);

                String parameters = requestLineAddr[1].substring(index + 1);
//            System.out.println(parameters);
                String[] parameterPair = parameters.split("&");
                if (null != parameterPair && !"".equals(parameterPair)) {
                    for (int i = 0; i < parameterPair.length; i++) {
                        String[] parameter = parameterPair[i].split("=");
                        if(parameter.length==2) {
                            parameterMapping.put(parameter[0], parameter[1]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    public String getParameter(String name){
        if(parameterMapping.containsKey(name)){
            return parameterMapping.get(name);
        }else {
            return "";
        }
    }
    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    @Override
    public String toString() {
        return "loopyRequest{" +
                "method='" + method + '\'' +
                ", uri='" + uri + '\'' +
                ", parameterMapping=" + parameterMapping +
                '}';
    }
}
